import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCDemo {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //1、创建数据源（DataSource）对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2、和数据库进行连接
        Connection connection = dataSource.getConnection();//需要处理受查异常SQLException

//        //3、构造sql语句
//        System.out.println("请输入学生id:");
//        int id = scanner.nextInt();
//        System.out.println("请输入学生姓名:");
//        String studentName = scanner.next();
//        String sql = "insert into student values("+id+",'"+studentName+"')";//采用字符串拼接的方式

        String sql = "insert into student values(?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,10);
        preparedStatement.setString(2,"李四");

        //4、执行SQL语句
        //进行增、删、改、建表删表等操作使用executeUpdate;进行查操作使用executeQuery()
        int affectRow = preparedStatement.executeUpdate();
        System.out.println("影响行数为："+ affectRow);

        //5、关闭连接等资源
        preparedStatement.close();
        connection.close();//先申请的资源后释放
    }
}
